#!/bin/bash

# CRMEB 开发环境快速启动脚本

echo "================================"
echo "CRMEB 后端服务启动脚本"
echo "================================"
echo ""

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# 后端项目根目录
BACKEND_DIR="$SCRIPT_DIR/../trading-center-backend"

# 检查后端目录是否存在
if [ ! -d "$BACKEND_DIR" ]; then
    echo "❌ 错误：找不到后端项目目录"
    echo "   预期路径: $BACKEND_DIR"
    exit 1
fi

cd "$BACKEND_DIR" || exit 1
echo "📁 工作目录: $(pwd)"
echo ""

# 检查 Docker 容器状态
echo "1. 检查 Docker 容器状态..."
MYSQL_STATUS=$(docker ps --filter "name=ryp_scm_mysql" --format "{{.Status}}" | grep -i "Up")
REDIS_STATUS=$(docker ps --filter "name=ryp_scm_redis" --format "{{.Status}}" | grep -i "Up")

if [ -z "$MYSQL_STATUS" ]; then
    echo "❌ MySQL 容器未运行，正在启动..."
    docker start ryp_scm_mysql
    sleep 5
else
    echo "✅ MySQL 容器正在运行"
fi

if [ -z "$REDIS_STATUS" ]; then
    echo "❌ Redis 容器未运行，正在启动..."
    docker start ryp_scm_redis
    sleep 3
else
    echo "✅ Redis 容器正在运行"
fi

echo ""
echo "2. 选择要启动的服务："
echo "   1) 管理后台 (Admin - 端口 8080)"
echo "   2) 前台服务 (Front - 端口 8081)"
echo "   3) 同时启动两个服务"
echo ""
read -p "请选择 [1-3]: " choice

case $choice in
    1)
        echo ""
        echo "启动管理后台服务..."
        cd crmeb-admin || exit 1
        mvn spring-boot:run -Dspring-boot.run.profiles=dev
        ;;
    2)
        echo ""
        echo "启动前台服务..."
        cd crmeb-front || exit 1
        mvn spring-boot:run -Dspring-boot.run.profiles=dev
        ;;
    3)
        echo ""
        echo "同时启动两个服务（使用新终端窗口）..."
        echo "管理后台将在后台运行，日志输出到 admin.log"
        echo "前台服务将在当前终端运行"
        echo ""
        
        # 在后台启动 admin
        cd crmeb-admin || exit 1
        nohup mvn spring-boot:run -Dspring-boot.run.profiles=dev > ../admin.log 2>&1 &
        ADMIN_PID=$!
        echo "✅ 管理后台已启动 (PID: $ADMIN_PID)，日志: admin.log"
        
        cd ..
        sleep 5
        
        # 在前台启动 front
        echo "✅ 正在启动前台服务..."
        cd crmeb-front || exit 1
        mvn spring-boot:run -Dspring-boot.run.profiles=dev
        ;;
    *)
        echo "无效选择，退出"
        exit 1
        ;;
esac

echo ""
echo "================================"
echo "访问地址："
echo "管理后台 API: http://localhost:8080"
echo "管理后台 Swagger: http://localhost:8080/doc.html"
echo "前台服务 API: http://localhost:8081"
echo "前台服务 Swagger: http://localhost:8081/doc.html"
echo "================================"

